<?php
/**
 * 根据麦子学院微信开发高级教程
 * 练习网页授权获取用户基本信息
 */

namespace Home\Controller;
use Think\Controller;
use Com\Wechat;
use Com\WechatAuth;

header("Content-type:text/html;chartset=utf-8");
class IndexController extends Controller {
    public function index(){
        $appid = 'wxb70359eb19266f10'; //AppID(应用ID)
        $token = 'ML168'; //微信后台填写的TOKEN
        $crypt = ''; //消息加密KEY（EncodingAESKey）
        
        /* 加载微信SDK */
        $wechat = new Wechat($token, $appid, $crypt);

        /* 获取请求信息 */
        $data = $wechat->request();

        if($data && is_array($data)){
            switch ($data['MsgType']) {
                case 'text':
                    $this->sendText($wechat, $data);
                    break;
                
                default:
                    # code...
                    break;
            }
        }

    }

    //回复文本消息
    private function sendText($wechat, $data){
        if(strstr($data['Content'],'文本')){
            $text = '这是一条文本消息的回复Demo';
            $this->logger($text);
            $wechat->replyText($text);
        }else if(strstr($data['Content'],'myself')){
            $this->users($wechat, $data);
        }
    }

    private function users($wechat, $data){
        $openid = $data['FromUserName'];
        $appid = 'wxb70359eb19266f10';
        $appsecret = 'd05e862df76a7401e0b2af0f06e8eade';
        $token = session('token');

        if($token){
            $wechatAuth = new WechatAuth($appid, $appsecret, $token);
        }else{
            $wechatAuth = new WechatAuth($appid, $appsecret);
            $accessToken = $wechatAuth->getAccessToken();
            $token = $accessToken['access_token'];
            session('token',$token);
        }

        $user = $wechatAuth->userInfo($openid);
        $text = "openid是：".$user['openid']."\n昵称：".$user['nickname']."\n城市：".$user['city'];

        $this->logger("发送给用户的信息：".$text);
        $wechat->ReplyText($text);

    }

    //网页授权获取用户基本信息 snsapi_userinfo\
    // 调用时URL后面加上 &iscode=1
    public function webUsers(){
        header("Content-type:text/html;charset=utf-8;");
        $appid = 'wxb70359eb19266f10';
        $appsecret = 'd05e862df76a7401e0b2af0f06e8eade';
        $wechatAuth = new WechatAuth($appid, $appsecret);
        if($_GET['iscode']){
            $url = "http://us.iqgzx.com/wechat/index.php?m=Home&c=Index&a=webUsers";
            $result = $wechatAuth->getRequestCodeURL($url);
            header("Location:{$result}");
        }else if($_GET['code']){
            $user = $wechatAuth->getAccessToken('code',$_GET['code']);
            $openid = $user['openid'];
            $users = $wechatAuth->getUserInfo($openid);
            $m = M('users');
            $data['openid'] = $users['openid'];
            $data['nickname'] = $users['nickname'];
            $result = $m->add($data);
            if($result){
                $text = "openid是：".$users['openid']."\n昵称：".$users['nickname']."\n城市：".$users['city'];
                dump($text);
            }
        }

        //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb70359eb19266f10&amp;redirect_uri=http%3A%2F%2Fus.iqgzx.com%2Fwechat%2Findex.php%3Fm%3DHome%26c%3DIndex%26a%3DwebUsers&amp;response_type=code&amp;scope=snsapi_userinfo#wechat_redirect
    }

    //网页授权获取用户基本信息 snsapi_base
    // 调用时URL后面加上 &iscode=1
    public function webUsersBase(){
        header("Content-type:text/html;charset=utf-8;");
        $appid = 'wxb70359eb19266f10';
        $appsecret = 'd05e862df76a7401e0b2af0f06e8eade';
        $wechatAuth = new WechatAuth($appid, $appsecret);
        if($_GET['iscode']){
            $url = "http://us.iqgzx.com/wechat/index.php?m=Home&c=Index&a=webUsers";
            $result = $wechatAuth->getRequestCodeURL($url, 123, 'snsapi_base');
            header("Location:{$result}");
        }else if($_GET['code']){
            $user = $wechatAuth->getAccessToken('code',$_GET['code']);
            $openid = $user['openid'];
            $users = $wechatAuth->getUserInfo($openid);
            $m = M('users');
            $data['openid'] = $users['openid'];
            $data['nickname'] = $users['nickname'];
            $result = $m->add($data);
            if($result){
                $text = "openid是：".$users['openid']."\n昵称：".$users['nickname']."\n城市：".$users['city'];
                dump($text);
            }
        }
    }

    // public function logger($content){
    //     $log = 'log.txt';
    //     $size = 100000;
    //     if(file_exists($log) && filesize($log) > $size){
    //         unlink($log);
    //     }

    //     file_put_contents($log, date('Y-m-d',time())."\n".$content."\n",FILE_APPEND);
    // }

    private function logger($content){
        $content = $content."\nREMOTE_ADDR：".$_SERVER['REMOTE_ADDR']."\nQUERY_STRING：".$_SERVER['QUERY_STRING'].'\n\n';

        $logSize = 10000;
        $log = 'log.txt';

        if(file_exists($log) && filesize($log) > $logSize){
            unlink($log);
        }

        file_put_contents($log,date('H:i:s')." ".$content."\n",FILE_APPEND); // "\n" 用双引号，单引号不识别
    }
}